package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.*;
import com.project.mapper.*;
import com.project.service.IBuyCarService;
import com.project.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ProductService implements IProductService {
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private IBuyCarMapper buyCarMapper;
    @Autowired
    private IBuyOrderMapper buyOrderMapper;
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IBuyInfoMapper buyInfoMapper;
    @Autowired
    private IBuyCarService buyCarService;
    @Autowired
    private ISellCarMapper sellCarMapper;
    @Autowired
    private ISellOrderMapper sellOrderMapper;
    @Autowired
    private ISellInfoMapper sellInfoMapper;
    @Override
    public void addProduct(ProductBean product,Integer userId,Integer num, String flag) {


        //问题，添加产品时，产品表中有，则不需要再次添加，直接添加到购物车
        //问题，判断产品是否重名================================
        if (flag.equals("update")) {
            //获取采购车对象
            QueryWrapper<BuyCarBean> qw = new QueryWrapper<BuyCarBean>();
            //判断库存中是否有这个产品，如果有，则在原有的购物车上添加数量
            ProductBean productBean =productMapper.selectById(product.getProductId());
            if (productBean != null){
                qw.eq("fk_productId", product.getProductId());
                qw.eq("fk_userId", userId);
                BuyCarBean buyCarBean = buyCarMapper.selectOne(qw);
                //!在采购车表中，查不到该笔采购车，但是库中有存在的商品，此处应该添加采购车
                //添加采购车和商品是两个方法
                if (buyCarBean != null){
                    //修改采购车对象的数量+num
                    buyCarBean.setNum(buyCarBean.getNum() + num);
                    buyCarMapper.updateById(buyCarBean);
                }else {
                    BuyCarBean buyCarBean1 = new BuyCarBean();
                    buyCarBean1.setPrice(product.getNewInPrice());//最新采购价
                    buyCarBean1.setProductId(product.getProductId());//产品id外键
                    buyCarBean1.setUserId(userId);//用户外键
                    buyCarBean1.setNum(num);//采购数量
                    buyCarMapper.insert(buyCarBean1);
                }
            }
        }
        if (flag.equals("add")) {
            //判断产品在产品表中是否存在
            ProductBean productBean =productMapper.selectById(product.getProductId());
            BuyCarBean buyCarBean = new BuyCarBean();
            if (productBean == null) {
                //添加产品
                productMapper.insert(product);
                //添加新的采购车对象--并且要set，当前登录用户，当前添加产品，num
//            product.setNum(0);//新添加的产品，库存默认为0--改在属性上了
                buyCarBean.setPrice(product.getNewInPrice());//最新采购价
                buyCarBean.setProductId(product.getProductId());//产品id外键
                buyCarBean.setUserId(userId);//用户外键
                buyCarBean.setNum(num);//采购数量
                buyCarMapper.insert(buyCarBean);
            }else {
                //添加新的采购车对象--并且要set，当前登录用户，当前添加产品，num
//            product.setNum(0);//新添加的产品，库存默认为0--改在属性上了
                buyCarBean.setPrice(product.getNewInPrice());//最新采购价
                buyCarBean.setProductId(product.getProductId());//产品id外键
                buyCarBean.setUserId(userId);//用户外键
                buyCarBean.setNum(num);//采购数量
                buyCarMapper.insert(buyCarBean);
            }

        }
    }

    @Override
    public String findByBuyCarId(Integer buyCarId) {
        return "";
    }

    @Override
    public void InStorage(String supplierName, Integer loginUserId) {
        //根据登录用户，查询对应的采购车，返还一个采购车集合
        List<BuyCarBean> buyCarList = buyCarService.findById(loginUserId);
        BuyOrderBean buyOrderBean = new BuyOrderBean();

        //只有当采购车有物品时，才能添加订单
        if (buyCarList!= null && buyCarList.size() > 0) {
            //问题，1、入库时，判断供应商名字是否重名--订单不需要判断重名，2、订单详情添加订单的id
            //添加采购订单
            buyOrderBean.setSupplierName(supplierName);
            buyOrderMapper.insert(buyOrderBean);
        }

        //一个空的采购详情信息集合
        List<BuyInfoBean> buyInfoBeanList = new ArrayList<>();

        //遍历采购车，循环添加明细信息，且注意：采购车数量和详情是一样的，但库存中数量需要累加！！！
       for (int i = 0; i < buyCarList.size(); i++) {
           BuyInfoBean buyInfoBean = new BuyInfoBean();//每一个采购车对应一个采购车详情
           buyInfoBean.setProductId(buyCarList.get(i).getProductId());//采购车的产品id-->采购详细的产品id
           buyInfoBean.setInPrice(buyCarList.get(i).getPrice());//采购车的价格
           //添加库存数量
           ProductBean productInS =productMapper.selectById(buyCarList.get(i).getProductId());//根据采购车，产品外键返回库存数量
           Integer storageNum = productInS.getNum()+buyCarList.get(i).getNum();//库存+采购车中的数量
           productInS.setNum(storageNum);//重新赋值
           productMapper.updateById(productInS);//完成修改

           buyInfoBean.setBuyOrderId(buyOrderBean.getBuyOrderId());//采购详情对应的采购订单
           buyInfoBean.setNum(buyCarList.get(i).getNum());//采购车的数量-->采购详细的数量
           buyInfoBean.setProductBeanInBuyInfo(buyCarList.get(i).getProductBeanInBuyCar());
           buyInfoMapper.insert(buyInfoBean);

           buyInfoBeanList.add(buyInfoBean);//添加到购买像详情新集合中
       }

        //添加采购订单，同时给其set供应商的名字，set采购详情信息集合，set采购者名字，set采购时间

        buyOrderBean.setBuyer(userMapper.selectById(loginUserId).getUserName());
        buyOrderBean.setDate(LocalDate.now());
        buyOrderBean.setBuyInfoBeanList(buyInfoBeanList);

        buyOrderMapper.updateById(buyOrderBean);

        //清空采购车，根据登录者id
        buyCarMapper.delete(new QueryWrapper<BuyCarBean>().eq("fk_userId", loginUserId));

    }

    @Override
    public void addProductInSellCar(String productId, Integer loginUserId) {
//        System.err.println(loginUserId);
        //判断销售车表中，是否存在相同商品
        QueryWrapper<SellCarBean> qw = new QueryWrapper<SellCarBean>();
        qw.eq("fk_productId", productId);
        qw.eq("fk_userId", loginUserId);
        SellCarBean exitSellCar = sellCarMapper.selectOne(qw);
        //判断
        if (exitSellCar == null) {
            //获取添加产品、登录用户
            ProductBean product = productMapper.selectById(productId);
            //设置到销售车上
            SellCarBean sellCarBean = new SellCarBean();
            sellCarBean.setProductId(productId);
            sellCarBean.setUserId(loginUserId);
            sellCarBean.setProductBeanInSellCar(product);
            sellCarBean.setUserBeanInSellCar(userMapper.selectById(loginUserId));
            sellCarMapper.insert(sellCarBean);

            //减少库存商品
            Integer kuCun = product.getNum();
            product.setNum(kuCun - 1);
            productMapper.updateById(product);

        }else {
            //添加销售车的数量+1
            exitSellCar.setNum(exitSellCar.getNum()+1);
            sellCarMapper.updateById(exitSellCar);

            //销售车中产品
            QueryWrapper<ProductBean> qwP = new QueryWrapper<ProductBean>();
            qwP.eq("pk_productId",productId);
            ProductBean productBean = productMapper.selectOne(qwP);
            productBean.setNum(productBean.getNum() -1);
            productMapper.updateById(productBean);
        }

    }

    @Override
    public void OutStorage(SellOrderBean sellOrderBean, Integer loginUserId) {
        //将出库车集合里的的东西，1.转到sellInfo中，2、添加一个sellOrder
        //添加销售订单
        sellOrderBean.setDate(LocalDate.now());//添加销售时间
        sellOrderMapper.insert(sellOrderBean);

        //获取销售车集合
        QueryWrapper<SellCarBean> qw = new QueryWrapper<SellCarBean>();
        qw.eq("fk_userId", loginUserId);
        List<SellCarBean> sellCarBeanList = sellCarMapper.selectList(qw);

        //将销售车的信息，传入到销售详情中
        List<SellInfoBean> sellInfoList = new ArrayList<>();
        for (int i = 0; i < sellCarBeanList.size(); i++) {
            SellInfoBean sellInfoBean = new SellInfoBean();//对应每一个销售车

            ProductBean productBean = productMapper.selectById(sellCarBeanList.get(i).getProductId());
            sellInfoBean.setDealPrice(productBean.getOutPrice());//采购价--获取销售车中的产品建议销售价

            sellInfoBean.setNum(sellCarBeanList.get(i).getNum());//销售数量--销售车中的出库数量
            sellInfoBean.setProductId(sellCarBeanList.get(i).getProductId());//产品id
            sellInfoBean.setProductBeanInSellInfo(sellCarBeanList.get(i).getProductBeanInSellCar());//产品对象
            sellInfoBean.setSellOrderId(sellOrderBean.getSellOrderId());//销售订单id
            sellInfoMapper.insert(sellInfoBean);//添加每一个销售详情到表中
            sellInfoList.add(sellInfoBean);//添加到销售详情的集合中
        }

        //获取总金额
//        Integer total = 0;
//        for (int i = 0; i < sellInfoList.size(); i++) {
//            Integer dealPrice = sellInfoList.get(i).getDealPrice();
//            int num = sellInfoList.get(i).getNum();
//            total += dealPrice * num * (i + 1);
//        }


        //设置销售订单的各个值，并修改
        sellOrderBean.setSeller(userMapper.selectById(loginUserId).getUserName());//销售员名字
//        sellOrderBean.setTotalPrice(total);//总金额
        sellOrderBean.setSellInfoBeanList(sellInfoList);//销售订单集合
        sellOrderMapper.updateById(sellOrderBean);

        //清空销售车
        sellCarMapper.delete(new QueryWrapper<SellCarBean>().eq("fk_userId", loginUserId));

    }

    @Override
    public IPage<ProductBean> findStorageByItem(Integer pageNO, String productType, String productName, Integer isPrice, Integer startNum, Integer endNum) {
        QueryWrapper<ProductBean> query = new QueryWrapper<>();

        if (StringUtils.isNotBlank(productName)) {
            query.like("p_name", productName);
        }
        if (StringUtils.isNotBlank(productType)) {
            query.eq("p_type", productType);
        }
//        if (isPrice != null && isPrice == 1) {
//            query.isNotNull("p_outPrice");
//        }
        if (isPrice != null && isPrice == 0) {
            query.isNull("p_outPrice");
        }
        if (startNum != null && startNum > 0) {
            query.ge("p_num", startNum);
        }
        if (endNum != null && endNum > 0){
            query.le("p_num", endNum);
        }

        IPage<ProductBean> iPage= productMapper.selectPage(new Page<ProductBean>(pageNO, 3), query);
        ;
        List<ProductBean> products=iPage.getRecords();

        List<ProductBean> productBeanList = new ArrayList<>();
        for (ProductBean productBean : products){
            if (productBean.getNum()>0){
                productBeanList.add(productBean);
            }
        }
        iPage.setRecords(productBeanList);
        return iPage;}


    @Override
    public ProductBean findProductByInStorage(Integer inStorageProductId) {
        return productMapper.selectById(inStorageProductId);
    }

    @Override
    public void updateInStorageProductPrice(String productId, Integer newPrice) {
        ProductBean productBean = productMapper.selectById(productId);
        productBean.setOutPrice(newPrice);
        productMapper.updateById(productBean);
    }

    @Override
    public List<ProductBean> findProductType() {
        return productMapper.findProductType();
    }
}
